import type { FunctionOption, MenuTree } from "@/api/auth/typing";
import { useMenuStore } from "@/store/menu";
import { useI18n } from "vue-i18n";
import { useRoute } from "vue-router";

export const usePath = () => {
  const { t } = useI18n();
  const route = useRoute();
  const menuStore = useMenuStore();
  /**递归获取页面路径工具 */
  const getPath = (menus: MenuTree, pa: MenuTree): boolean => {
    for (const item of menus) {
      pa.push(item);
      if ("functionId" in item) {
        if (item.accessPath == route.fullPath) {
          return true;
        }
      } else if ("menuId" in item) {
        if (item.functions) {
          const result = getPath(item.functions, pa);
          if (result) return true;
        }
        if (item.menus) {
          const result = getPath(item.menus, pa);
          if (result) return true;
        }
      }
      pa.pop();
    }
    return false;
  };
  /**获取页面菜单树路径 */
  const getTreePath = (): MenuTree => {
    const path: MenuTree = [];
    getPath(menuStore.menus, path);
    return path;
  };
  /**获取当前功能数据 */
  const getCurrentFunction = (): FunctionOption => {
    const paths = getTreePath();
    return paths.pop() as FunctionOption;
  };
  /**模糊搜索菜单/功能 */
  const searchFns = (
    keyword: string,
    menus: MenuTree = menuStore.menus,
    paths: MenuTree = []
  ) => {
    const fns: MenuTree[] = [];
    for (const item of menus) {
      if ("functionId" in item) {
        if (
          item.functionName.includes(keyword) ||
          t(item.localeKey).includes(keyword)
        ) {
          fns.push([...paths, item]);
        }
      } else if ("menuId" in item) {
        if (
          item.menuName.includes(keyword) ||
          t(item.localeKey).includes(keyword)
        ) {
          fns.push(...item.functions.map((m) => [...paths, item, m]));
          if (item.menus.length) {
            fns.push(...searchFns("", item.menus, [...paths, item]));
          }
        } else {
          if (item.functions.length) {
            fns.push(...searchFns(keyword, item.functions, [...paths, item]));
          }
          if (item.menus.length) {
            fns.push(...searchFns(keyword, item.menus, [...paths, item]));
          }
        }
      }
    }
    return fns;
  };
  return {
    searchFns,
    getTreePath,
    getCurrentFunction,
  };
};
